package com.frogs.ucenter.controller;

import java.io.FileOutputStream;
import java.util.List;
import java.util.SortedMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.frogs.framework.base.web.BaseController3;
import com.frogs.framework.util.DWZResponse;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.RenderUtil;
import com.frogs.framework.util.date.DateUtil;
import com.frogs.framework.web.HttpRequestInfo;
import com.frogs.system.util.FormSelectLoader;
import com.frogs.system.util.UserAccountInfoStatusEnum;
import com.frogs.ucenter.entity.UserRechargeRecord;
import com.frogs.ucenter.entity.UserRechargeRecordWithUser;
import com.frogs.ucenter.service.UserRechargeRecordService;

@Controller
@RequestMapping("/admin/userRechargeRecord")
public class UserRechargeRecordController extends BaseController3 {
    private static final String ROOT_VIEW = "admin/userRechargeRecord";

    private static final String HOME_VIEW = "admin/userRechargeRecord/home";

    private static final String EDIT_VIEW = "admin/userRechargeRecord/edit";
    
    private static final String EXPORT_EXCEL = "/export";
    
    private static SortedMap<Integer, String> payStatusMap = FormSelectLoader.getPayStatusformMap();
    
    @Autowired
    private UserRechargeRecordService userRechargeRecordService;

    @RequestMapping()
    public String listUserRechargeRecord(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap( request, model, true );
        if(model.containsKey("eqEmail")) {
    	    model.put("eqIsEmailValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
        }
        
        if(model.containsKey("eqPhone")) {
    	    model.put("eqIsPhoneValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
        }
        model.put("orderByClause", "recharge_time desc");
        
        getPageList( model );
        return HOME_VIEW;
    }
    
    

    @RequestMapping(EDIT)
    public String createUserRechargeRecord(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap( request, model, false );
        Integer id = reqInfo.getIntParameter( "id", -1 );
        if( id > 0 ){
            model.put( "model",userRechargeRecordService.getById( id ) ); 
        }
        return EDIT_VIEW;
    }

    @RequestMapping(ADD)
    public String saveUserRechargeRecord(HttpServletRequest request, HttpServletResponse response, ModelMap model, UserRechargeRecord userRechargeRecord) {
        setRequestModelMap(request, model, false);
        DWZResponse.Builder builder;
        try {
            userRechargeRecordService.insert( userRechargeRecord ); 
            builder = DWZResponse.getSucessBuilder("新增成功");
        } catch (Exception e) {
            builder = DWZResponse.getFailBuilder("新增失败" + e.getMessage());
        }
        RenderUtil.renderHtml(builder.build().toString(), response);
        return null;
    }

    @RequestMapping(SHOW)
    public String showUserRechargeRecord(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer id = reqInfo.getIntParameter( "id", -1 );
        if( id > 0 ){
            model.addAttribute( userRechargeRecordService.getById( id ) ); 
        }
        setRequestModelMap(request, model);
        return null;
    }

    @RequestMapping(UPDATE)
    public String updateUserRechargeRecord(HttpServletRequest request, HttpServletResponse response, ModelMap model, UserRechargeRecord userRechargeRecordNew) throws Exception {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer id = reqInfo.getIntParameter( "id", -1 );
        if( id > 0 ){
            DWZResponse.Builder builder;
            try {
                UserRechargeRecord userRechargeRecord = userRechargeRecordService.getById( id ); 
                PropertyUtils.copyProperties(userRechargeRecord, userRechargeRecordNew);
                userRechargeRecordService.update( userRechargeRecord ); 
                model.clear();
                builder = DWZResponse.getSucessBuilder("更新成功");
            } catch (Exception e) {
                builder = DWZResponse.getFailBuilder("更新失败" + e.getMessage());
            }
            RenderUtil.renderHtml(builder.build().toString(), response);
        }
        return null;
    }

    @RequestMapping(DELETE)
    public String deleteUserRechargeRecord(HttpServletRequest request, HttpServletResponse response, ModelMap model, String inIdList) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap(request, model);
        DWZResponse.Builder builder;
        try {
            String[] idArray = inIdList.split(",");
            model.put("inIdList", idArray);
            userRechargeRecordService.delete( model ); 
            builder = DWZResponse.getSucessBuilder("删除信息成功");
        } catch (Exception e) {
            builder = DWZResponse.getFailBuilder("删除信息失败" + e.getMessage());
        }
        RenderUtil.renderHtml(builder.build().toString(), response);
        model.clear();
        return null;
    }

    private PageList<UserRechargeRecordWithUser> getPageList(ModelMap model) {
        PageList<UserRechargeRecordWithUser> userRechargeRecordList = userRechargeRecordService.listRecharge( model, Integer.parseInt(model.get("pageNum").toString()), Integer.parseInt(model.get("numPerPage").toString()) ); 
        model.put("userRechargeRecordList",userRechargeRecordList);
        model.put("pageTurn",userRechargeRecordList.getPageTurn());
        return userRechargeRecordList;
    }
    
    private List<UserRechargeRecordWithUser> getList(ModelMap model) {
        List<UserRechargeRecordWithUser> userRechargeRecordList = userRechargeRecordService.listRecharge( model, 1, 100000); 
        return userRechargeRecordList;
    }
    
    @RequestMapping(EXPORT_EXCEL)
    public ModelMap exportExcel(HttpServletRequest request, ModelMap model) {
    	HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap(request, model, true);
        if(model.containsKey("eqEmail")) {
    	    model.put("eqIsEmailValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
        }
        
        if(model.containsKey("eqPhone")) {
    	    model.put("eqIsPhoneValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
        }
        model.put("orderByClause", "recharge_time desc");
        
        List<UserRechargeRecordWithUser> exportObjs = getList(model);//hospitalDoctorRelationDao.exportHospitalDoctor(params);
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet();
        createHead(sheet);
        String name = "用户充值记录";
        int index = 1 ;
        for(UserRechargeRecordWithUser obj : exportObjs){
        	exportWrite(sheet, obj, index);
        	index++;
            if(index % 100 == 0){
                try{
                    Thread.sleep(1000);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        
        try{
            String path = request.getSession().getServletContext().getRealPath("/");
            String fileName = "/export/" + name + ".xls";
            FileOutputStream fileOut = new FileOutputStream(path+fileName);
            wb.write(fileOut);
            fileOut.close();
            model.put("fileName", fileName);
        }catch (Exception e){
            e.printStackTrace();
        }
        return model;
    }
    
    public void exportWrite(HSSFSheet sheet,UserRechargeRecordWithUser obj,int rowIndex){
        HSSFRow row = sheet.createRow(rowIndex);
        row.createCell(0).setCellValue(obj.getAccountName());
        row.createCell(1).setCellValue(obj.getPhone());
        row.createCell(2).setCellValue(obj.getEmail());
        row.createCell(3).setCellValue(obj.getRechargeMoney().toString());
        row.createCell(4).setCellValue(obj.getRechargeCard());
        row.createCell(5).setCellValue(DateUtil.formatDate(obj.getRechargeTime(), "yyyy-MM-dd HH:mm:ss"));
        row.createCell(6).setCellValue(obj.getRechargeFrom());
        row.createCell(7).setCellValue(payStatusMap.get(obj.getStatus()));
    }
    
    public void createHead(HSSFSheet sheet){
        HSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("用户名");
        row.createCell(1).setCellValue("手机号码");
        row.createCell(2).setCellValue("邮箱");
        row.createCell(3).setCellValue("充值金额");
        row.createCell(4).setCellValue("充值卡");
        row.createCell(5).setCellValue("充值时间");
        row.createCell(6).setCellValue("充值来源");
        row.createCell(7).setCellValue("状态");
    }
}